<template>
  <div class="activity-list">
    <a-page-header
      title="活动管理"
      sub-title="管理系统中的活动，包括新增、编辑和删除等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="活动名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入活动名称" allowClear />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allowClear
            style="width: 150px"
          >
            <a-select-option :value="0">投稿期</a-select-option>
            <a-select-option :value="1">公示期</a-select-option>
            <a-select-option :value="2">投票期</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="handleAdd" v-permission="'content:activity:add'">
              <template #icon><plus-outlined /></template>新增活动
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="tableData" 
        :loading="loading" 
        :pagination="{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="handleEdit(record)" v-permission="'content:activity:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-popconfirm
                title="确定要删除该活动吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'content:activity:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
            </a-tag>
            </template>
            <template v-else-if="column.key === 'cover'">
              <img v-if="record.coverImage" :src="`/api${record.coverImage}`" alt="封面" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;" />
              <span v-else>-</span>
            </template>
        </template>
    </a-table>

    <!-- 新增/编辑活动弹窗 -->
    <a-modal
      :title="dialogTitle"
      :visible="dialogVisible"
      @ok="submitForm"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
      width="700px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="活动名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入活动名称" />
        </a-form-item>
        <a-form-item label="活动分类" name="categoryId">
          <a-select
            v-model:value="form.categoryId"
            placeholder="请选择活动分类"
            style="width: 100%"
          >
            <a-select-option
              v-for="category in categoryList"
              :key="category.id"
              :value="category.id"
            >
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="活动封面" name="coverImage">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="/api/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl.startsWith('data:') ? imageUrl : `/api${imageUrl}`" alt="cover" style="width: 100%; height: 100%; border-radius: 8px; object-fit: cover" />
            <div v-else>
              <loading-outlined v-if="imageLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="活动描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入活动描述" :rows="4" />
        </a-form-item>
        <a-form-item label="活动规则" name="rules">
          <a-textarea v-model:value="form.rules" placeholder="请输入活动规则" :rows="4" />
        </a-form-item>
        <a-form-item label="开始时间" name="startTime">
          <a-date-picker
            v-model:value="form.startTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="结束时间" name="endTime">
          <a-date-picker
            v-model:value="form.endTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="活动状态" name="status">
          <a-select
            v-model:value="form.status"
            placeholder="请选择活动状态"
            style="width: 100%"
          >
            <a-select-option :value="0">投稿期</a-select-option>
            <a-select-option :value="1">公示期</a-select-option>
            <a-select-option :value="2">投票期</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'ActivityList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LoadingOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const formRef = ref(null);
    const loading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增活动');
    const isEdit = ref(false);
    const modalLoading = ref(false);
    const imageUrl = ref('');
    const imageLoading = ref(false);
    const fileList = ref([]);
    
    const searchForm = reactive({
      name: '',
      status: undefined,
    });
    
    // 分类列表数据
    const categoryList = ref([]);

    // 获取分类列表
    const getCategoryList = () => {
      axios.get('/api/category/list')
        .then(response => {
          if (response.data.code === 200) {
            categoryList.value = response.data.data;
          } else {
            message.error(response.data.message || '获取分类列表失败');
          }
        })
        .catch(error => {
          console.error('获取分类列表失败:', error);
          message.error('获取分类列表失败');
        });
    };

    const form = reactive({
      id: '',
      name: '',
      coverImage: '',
      description: '',
      rules: '',
      startTime: null,
      endTime: null,
      status: 0,
      participantCount: 0,
      artworkCount: 0,
      categoryId: undefined // 新增分类ID字段
    });
    
    const rules = {
      name: [
        { required: true, message: '请输入活动名称', trigger: 'blur' },
        { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
      ],
      coverImage: [
        { required: true, message: '请上传活动封面', trigger: 'change' }
      ],
      description: [
        { max: 1000, message: '活动描述不能超过1000个字符', trigger: 'blur' }
      ],
      rules: [
        { max: 2000, message: '活动规则不能超过2000个字符', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择活动分类', trigger: 'change' }
      ],
      startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
      ],
      endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        {
          validator: (rule, value) => {
            if (form.startTime && value && dayjs(value).isBefore(dayjs(form.startTime))) {
              return Promise.reject('结束时间不能早于开始时间');
            }
            return Promise.resolve();
          },
          trigger: 'change'
        }
      ]
    };

    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '活动名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '分类',
        dataIndex: 'categoryName',
        key: 'categoryName',
      },
      {
        title: '封面',
        dataIndex: 'coverImage',
        key: 'cover',
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
      },
      {
        title: '作品数量',
        dataIndex: 'artworkCount',
        key: 'artworkCount',
        width: 100,
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
      }
    ];

    // 获取活动列表
    const getActivityList = (page = currentPage.value, size = pageSize.value) => {
      loading.value = true;
      const params = {
        current: page,
        size: size,
        name: searchForm.name,
        status: searchForm.status
      };
      
      axios.get('/api/activity/page', { params })
        .then(response => {
          if (response.data.code === 200) {
            tableData.value = response.data.data.records;
            total.value = response.data.data.total;
            currentPage.value = page;
            pageSize.value = size;
          } else {
            message.error(response.data.message || '获取活动列表失败');
          }
        })
        .catch(error => {
          console.error('获取活动列表失败:', error);
          message.error('获取活动列表失败');
        })
        .finally(() => {
          loading.value = false;
        });
    };

    // 表格变化事件
    const handleTableChange = (pag) => {
      getActivityList(pag.current, pag.pageSize);
    };

    // 搜索
    const handleSearch = () => {
      getActivityList(1, pageSize.value);
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.name = '';
      searchForm.status = undefined;
      handleSearch();
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '投稿期';
        case 1: return '公示期';
        case 2: return '投票期';
        default: return '未知';
      }
    };

    // 获取状态颜色
    const getStatusColor = (status) => {
      switch (status) {
        case 0: return 'orange';
        case 1: return 'green';
        case 2: return 'red';
        default: return 'default';
      }
    };

    const getBase64 = (img, callback) => {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
      }
      return isJpgOrPng && isLt2M;
    };

    const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        imageLoading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        if (info.file.response.code === 200) {
          form.coverImage = info.file.response.data;
          getBase64(info.file.originFileObj, (base64Url) => {
            imageUrl.value = base64Url;
            imageLoading.value = false;
          });
        } else {
          message.error('上传失败');
          imageLoading.value = false;
        }
      }
      if (info.file.status === 'error') {
        imageLoading.value = false;
        message.error('上传失败');
      }
    };

    // 新增活动
    const handleAdd = () => {
      dialogTitle.value = '新增活动';
      isEdit.value = false;
      form.id = '';
      form.name = '';
      form.coverImage = '';
      form.description = '';
      form.rules = '';
      form.startTime = null;
      form.endTime = null;
      form.status = 0;
      form.participantCount = 0;
      form.artworkCount = 0;
      form.categoryId = null; // 重置活动分类ID
      imageUrl.value = '';
      dialogVisible.value = true;
    };

    // 编辑活动
    const handleEdit = (record) => {
      dialogTitle.value = '编辑活动';
      isEdit.value = true;
      form.id = record.id;
      form.name = record.name;
      form.coverImage = record.coverImage;
      form.description = record.description;
      form.rules = record.rules;
      form.startTime = dayjs(record.startTime);
      form.endTime = dayjs(record.endTime);
      form.status = record.status;
      form.participantCount = record.participantCount;
      form.artworkCount = record.artworkCount;
      form.categoryId = record.categoryId; // 设置活动分类ID
      imageUrl.value = record.coverImage;
      dialogVisible.value = true;
    };

    // 删除活动
    const handleDelete = (id) => {
      axios.delete(`/api/activity/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            message.success('删除成功');
            getActivityList();
          } else {
            message.error(response.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除失败:', error);
          message.error('删除失败');
        });
    };

    // 弹窗取消
    const handleModalCancel = () => {
      dialogVisible.value = false;
    };

    // 提交表单
    const submitForm = () => {
      formRef.value.validate().then(() => {
        modalLoading.value = true;
        
        const submitData = {
          ...form,
          startTime: form.startTime ? dayjs(form.startTime).format('YYYY-MM-DD HH:mm:ss') : null,
          endTime: form.endTime ? dayjs(form.endTime).format('YYYY-MM-DD HH:mm:ss') : null
        };

        if (isEdit.value) {
          // 编辑
          axios.put(`/api/activity/${form.id}`, submitData)
            .then(response => {
              if (response.data.code === 200) {
                message.success('更新成功');
                dialogVisible.value = false;
                getActivityList();
              } else {
                message.error(response.data.message || '更新失败');
              }
            })
            .catch(error => {
              console.error('更新失败:', error);
              message.error('更新失败');
            })
            .finally(() => {
              modalLoading.value = false;
            });
        } else {
          // 新增
          axios.post('/api/activity', submitData)
            .then(response => {
              if (response.data.code === 200) {
                message.success('创建成功');
                dialogVisible.value = false;
                getActivityList();
              } else {
                message.error(response.data.message || '创建失败');
              }
            })
            .catch(error => {
              console.error('创建失败:', error);
              message.error('创建失败');
            })
            .finally(() => {
              modalLoading.value = false;
            });
        }
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    onMounted(() => {
      getActivityList();
      getCategoryList();
    });

    return {
      formRef,
      loading,
      tableData,
      total,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      isEdit,
      modalLoading,
      searchForm,
      form,
      rules,
      columns,
      getActivityList,
      handleTableChange,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleModalCancel,
      submitForm,
      getStatusText,
      getStatusColor,
      imageUrl,
      imageLoading,
      fileList,
      beforeUpload,
      handleChange,
      categoryList,
      getCategoryList,
    };
  }
});
</script>

<style scoped>
.activity-list {
  background-color: transparent;
}

.search-card {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}
</style>